<template>
  <div class="profile">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="profile-card">
          <div class="avatar-container">
            <el-avatar :src="userInfo.avatar" :size="100">
              {{ userInfo.nickname?.charAt(0) }}
            </el-avatar>
            <el-button type="primary" size="small" @click="changeAvatar" style="margin-top: 15px;">
              更换头像
            </el-button>
          </div>
          <div class="user-info">
            <h3>{{ userInfo.nickname }}</h3>
            <p>{{ userInfo.username }}</p>
            <p class="user-role">{{ userInfo.roles?.join(', ') }}</p>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人资料</span>
            </div>
          </template>
          
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicRules"
                label-width="100px"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户名" prop="username">
                      <el-input v-model="basicForm.username" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="昵称" prop="nickname">
                      <el-input v-model="basicForm.nickname" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="basicForm.email" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="basicForm.phone" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-form-item label="性别">
                  <el-radio-group v-model="basicForm.gender">
                    <el-radio label="male">男</el-radio>
                    <el-radio label="female">女</el-radio>
                    <el-radio label="secret">保密</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="个人简介">
                  <el-input
                    v-model="basicForm.bio"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入个人简介"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="saveBasicInfo">保存</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="安全设置" name="security">
              <el-form
                ref="securityFormRef"
                :model="securityForm"
                :rules="securityRules"
                label-width="120px"
              >
                <el-form-item label="原密码" prop="oldPassword">
                  <el-input
                    v-model="securityForm.oldPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="securityForm.newPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input
                    v-model="securityForm.confirmPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="changePassword">修改密码</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
   
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="更换头像"
      width="500px"
    >
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="tempAvatar" :src="tempAvatar" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="avatar-hint">
          <p>支持 JPG、PNG 格式，大小不超过 2MB</p>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="avatarDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAvatarChange">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { updateUserInfo, changePassword } from '@/api/user'
import type { FormInstance } from 'element-plus'

interface UserInfo {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  avatar: string
  roles: string[]
  gender: string
  bio: string
}

const userStore = useUserStore()
const activeTab = ref('basic')
const avatarDialogVisible = ref(false)
const tempAvatar = ref('')
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_URL + '/avatar'
const uploadHeaders = {
  Authorization: `Bearer ${userStore.token}`
}

// 表单引用
const basicFormRef = ref<FormInstance>()
const securityFormRef = ref<FormInstance>()
const preferencesFormRef = ref<FormInstance>()

// 用户信息
const userInfo = ref<UserInfo>({
  id: 0,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  roles: [],
  gender: 'secret',
  bio: ''
})

// 基本信息表单
const basicForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 'secret',
  bio: ''
})

// 安全设置表单
const securityForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 偏好设置表单
const preferencesForm = reactive({
  language: 'zh-CN',
  theme: 'light',
  notifications: ['email']
})

// 表单验证规则
const basicRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const securityRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== securityForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
} as any

const loadUserInfo = () => {
  if (userStore.userInfo) {
    const user = userStore.userInfo
    userInfo.value = {
      ...user,
      gender: user.gender || 'secret',
      bio: user.bio || ''
    }
    
    // 更新表单数据
    basicForm.username = user.username
    basicForm.nickname = user.nickname
    basicForm.email = user.email
    basicForm.phone = user.phone || ''
    basicForm.gender = user.gender || 'secret'
    basicForm.bio = user.bio || ''
  }
}

const saveBasicInfo = async () => {
  if (!basicFormRef.value) return
  
  await basicFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      const data = {
        nickname: basicForm.nickname,
        email: basicForm.email,
        phone: basicForm.phone,
        gender: basicForm.gender,
        bio: basicForm.bio
      }
      
      await updateUserInfo(userInfo.value.id, data)
      ElMessage.success('个人信息更新成功')
      
      // 更新用户状态
      userStore.userInfo = {
        ...userStore.userInfo!,
        ...data
      }
      
      // 更新本地数据
      userInfo.value = {
        ...userInfo.value,
        ...data
      }
    } catch (error) {
      ElMessage.error('更新个人信息失败')
      console.error(error)
    }
  })
}

const changePassword = async () => {
  if (!securityFormRef.value) return
  
  await securityFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      await changePassword({
        old_password: securityForm.oldPassword,
        new_password: securityForm.newPassword
      })
      ElMessage.success('密码修改成功')
      
      // 重置表单
      securityForm.oldPassword = ''
      securityForm.newPassword = ''
      securityForm.confirmPassword = ''
    } catch (error) {
      ElMessage.error('密码修改失败')
      console.error(error)
    }
  })
}

const savePreferences = () => {
  ElMessage.success('偏好设置保存成功')
  // 这里应该调用API保存偏好设置
}

const changeAvatar = () => {
  avatarDialogVisible.value = true
  tempAvatar.value = userInfo.value.avatar
}

const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    tempAvatar.value = response.data.url
  } else {
    ElMessage.error('头像上传失败')
  }
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  
  return isJPG && isLt2M
}

const confirmAvatarChange = async () => {
  try {
    // 这里应该调用API更新用户头像
    userInfo.value.avatar = tempAvatar.value
    userStore.userInfo = {
      ...userStore.userInfo!,
      avatar: tempAvatar.value
    }
    avatarDialogVisible.value = false
    ElMessage.success('头像更换成功')
  } catch (error) {
    ElMessage.error('头像更换失败')
    console.error(error)
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped lang="scss">
.profile {
  padding: 20px;
  
  .profile-card {
    text-align: center;
    
    .avatar-container {
      margin-bottom: 20px;
    }
    
    .user-info {
      h3 {
        margin: 10px 0;
        font-size: 18px;
        color: #303133;
      }
      
      p {
        margin: 5px 0;
        color: #606266;
        font-size: 14px;
      }
      
      .user-role {
        color: #409EFF;
        font-weight: 500;
      }
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .avatar-upload {
    text-align: center;
    
    :deep(.avatar-uploader) {
      display: inline-block;
      
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          border-color: #409EFF;
        }
      }
    }
    
    .avatar-preview {
      width: 120px;
      height: 120px;
      display: block;
      border-radius: 6px;
      object-fit: cover;
    }
    
    .avatar-hint {
      margin-top: 15px;
      color: #909399;
      font-size: 12px;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>